﻿using AbpApplication.Expand;
using AbpApplication.Flurl;
using AbpApplication.InPut;
using AbpEntityFrameworkcore.DbContext;
using AbpToDomain.CustomEntityInfo;
using AbpToDomain.EntityInfo;
using AbpToDomain.View;
using Castle.Core.Logging;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
using NLog;
using SingalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;
using wms_wpf.Apiservice;

namespace AbpApplication.AppServices
{

    public class EssService : ApplicationService, IEssService
    {
        private readonly IRepository<TaskOrder> TaskOrder_res;
        private readonly IRepository<Box> box_res;
        private readonly IRepository<WarehouseLine> warehouse_line_res;
        private readonly IRepository<InlethouseLine> inlethouseline_res;
        private readonly IRepository<SowingWallLine> sowingwallline_res;
        private readonly ILoginHelper loginHelper;
        private readonly IBaseService baseService;
        private readonly IToOutSideInterFace toOutSideInterFace;
        private readonly IRepository<lognote> LogNote_res;
        private readonly IRepository<Conveyorline> conveyorline_res;
        private readonly MyDbContext context;



        public EssService(IRepository<TaskOrder> taskOrder_res, IRepository<Box> box_res,
            IRepository<WarehouseLine> warehouse_line_res,
            ILoginHelper loginHelper,
            IBaseService baseService,
            IRepository<InlethouseLine> inlethouseline_res,
            IRepository<lognote> logNote_res, MyDbContext context,
            IRepository<SowingWallLine> sowingwallline_res,
          
            IToOutSideInterFace toOutSideInterFace)
        {
            TaskOrder_res = taskOrder_res;
            this.box_res = box_res;
            this.LogNote_res = logNote_res;
            this.warehouse_line_res = warehouse_line_res;
            this.loginHelper = loginHelper;
            this.baseService = baseService;
            this.inlethouseline_res = inlethouseline_res;
            this.context = context;
            this.sowingwallline_res = sowingwallline_res;
            this.toOutSideInterFace = toOutSideInterFace;
        }



        public async Task<ApiResponse> AbnormalCapture(InPut_EssService2 InPut)
        {
            return new ApiResponse("ok", true, null);
        }//异常回调
        public async Task<ApiResponseEss> TaskStatusChange(InPut_EssService InPut)
        {
            try
            {
                loginHelper.LoginInfoAsync(InPut, $"TaskStatusChange任务回调-日志-{InPut.taskCode + "msg：" +
                   InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}");
                //log
                lognote lognote = new lognote()
                {
                    DateTime = DateTime.Now,
                    User = "ESS",
                    Type = "ESS异常检查-出库",
                    Note = ($"TaskStatusChange任务回调-日志-{InPut.taskCode + "msg：" +
                   InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}")
                };
                await context.AddAsync(lognote);
                if (InPut.eventType == "task")
                {
                    if (InPut.status.Contains("success"))
                    {
                        TaskOrder taskOrder = await context.taskOrders.FirstOrDefaultAsync(x => x.TaskOrderCode == InPut.taskCode);
                        if (taskOrder == null)
                        {
                            //log
                            lognote lognotetasknull = new lognote()
                            {
                                DateTime = DateTime.Now,
                                User = "ESS",
                                Type = "ESS异常检查-出库",
                                Note = ($"TaskStatusChange任务回调-未查询到任务-{InPut.taskCode + "msg：" +
           InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}")
                            };
                            await context.AddAsync(lognotetasknull);
                            loginHelper.LoginInfoAsync(InPut, $"TaskStatusChange任务回调-未查询到任务-{InPut.taskCode + "msg：" +
           InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}");
                            await context.SaveChangesAsync();
                            return new ApiResponseEss(0, "success", "fail");
                        }
                        if (taskOrder.Type == "出库")
                        {
      
                            loginHelper.LoginInfoAsync(InPut, $"TaskStatusChange任务回调-到出库了-{InPut.taskCode + "msg：" +
   InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}");



                            //excuting
                            Box box = await context.boxs.FirstOrDefaultAsync(x => x.Id_Box == taskOrder.Id_Box);
                            WarehouseLine warehouseLine = await context.warehouseLines.FirstOrDefaultAsync(x => x.WarehouseLineCode == taskOrder.WarehouseCode);
                            InlethouseLine inlethouseLine = await context.inlethousesLine.FirstOrDefaultAsync(x => x.InlethouseLineCode == taskOrder.InlethouseCode);

                            //备用
                            Conveyorline conveyorline = new Conveyorline();
                            conveyorline.BoxCode = box.BoxCode;
                            conveyorline.Machine = taskOrder.Machine.ToString();
                            conveyorline.CreateTime = DateTime.Now;
                            context.conveyorlines.Add(conveyorline);

                            warehouseLine.IsOccupy = false;
                            inlethouseLine.Box = box;
                            box.WarehouseLine = null;
                            box.Id_WarehouseLine = null;
                            box.Id_InlethouseLine = null;
                            box.InlethouseLine = null;
                            inlethouseLine.Box = null;
                            inlethouseLine.IsOccupy = false;
                            context.taskOrders.Remove(taskOrder);

                            //log

                            loginHelper.LoginInfoAsync(InPut, $"TaskStatusChange任务回调-出库成功-{InPut.taskCode + "msg：" +
              InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}");

                            await context.SaveChangesAsync();
                            return new ApiResponseEss(0, "success", "success1");

                        }
                        if (taskOrder.Type == "入库")
                        {
                            
                            //excuting
                            WarehouseLine warehouseLine = await context.warehouseLines.FirstOrDefaultAsync(x => x.WarehouseLineCode == taskOrder.WarehouseCode);
                            Box box = await context.boxs.FirstOrDefaultAsync(x => x.Id_Box == taskOrder.Id_Box);
                            box.Id_WarehouseLine = warehouseLine.Id_WarehouseLine;
                            box.WarehouseLine = warehouseLine;
                            context.taskOrders.Remove(taskOrder);
                            //备用
                            Conveyorline conveyorline = await context.conveyorlines.FirstOrDefaultAsync(x => x.BoxCode == box.BoxCode);
                            if (conveyorline != null)
                            {
                                context.conveyorlines.Remove(conveyorline);
                            }

                            //log
                            lognote inboundsuccess = new lognote()
                            {
                                DateTime = DateTime.Now,
                                User = "ESS",
                                Type = "ESS异常检查-出库",
                                Note = ($"TaskStatusChange任务回调-入库成功-{InPut.taskCode + "msg：" +
                 InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}")
                            };
                            await context.AddAsync(inboundsuccess);
                            loginHelper.LoginInfoAsync(InPut, $"TaskStatusChange任务回调-入库成功-{InPut.taskCode + "msg：" +
                            InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}");
                            //savachanges
                            await context.SaveChangesAsync();
                            return new ApiResponseEss(0, "success", "success2");
                        }

                    }
                    if (InPut.status == "cancel")
                    {
                        TaskOrder taskOrder = await context.taskOrders.FirstOrDefaultAsync(x => x.TaskOrderCode == InPut.taskCode);
                        if (taskOrder == null)
                        {

                            return new ApiResponseEss(0, "success", "Unable");
                        }
                        lognote lognote2 = new lognote()
                        {
                            DateTime = DateTime.Now,
                            User = "ESS",
                            Type = "取消任务",
                            Note = "任务编号：" + InPut.taskCode + "msg：" + InPut.message + "事件类型：" + InPut.eventType + "容器:" + InPut.containerCode +
                       "站点:" + InPut.stationCode + "状态：" + InPut.status
                        };


                        await context.AddAsync(lognote2);
                        if (taskOrder.Type == "入库")
                        {
                            loginHelper.LoginInfoAsync(lognote2, $"task+cancel+入库{InPut.taskCode}");
                            WarehouseLine warehouseLine = await context.warehouseLines.FirstOrDefaultAsync(x => x.WarehouseLineCode == taskOrder.WarehouseCode);
                            warehouseLine.IsOccupy = false;
                            context.taskOrders.Remove(taskOrder);
                            loginHelper.LoginInfoAsync("ss", $"TaskStatusChange-任务失败/取消了+{taskOrder.Id_Box + taskOrder.WarehouseCode + taskOrder.TaskOrderCode}");
                            await context.SaveChangesAsync();
                            return new ApiResponseEss(0, "success", "cancel");
                        }
                    }
                }
                if (InPut.eventType == "tote_load")
                {
                    if (InPut.status.Contains("success"))
                    {
                        TaskOrder taskOrder = await context.taskOrders.FirstOrDefaultAsync(x => x.TaskOrderCode == InPut.taskCode);
                        if (taskOrder == null)
                        {
                            //log
                            lognote lognotetasknull = new lognote()
                            {
                                DateTime = DateTime.Now,
                                User = "ESS",
                                Type = "ESS异常检查",
                                Note = ($"TaskStatusChange任务回调-未查询到任务-{InPut.taskCode + "msg：" +
           InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}")
                            };
                            await context.AddAsync(lognotetasknull);
                            loginHelper.LoginInfoAsync(InPut, $"TaskStatusChange任务回调-未查询到任务-{InPut.taskCode + "msg：" +
           InPut.message + "事件类型：" + InPut.eventType + "状态：" + InPut.status}");
                            await context.SaveChangesAsync();
                            return new ApiResponseEss(0, "success", "fail");
                        }
                        if (taskOrder.Type == "入库")
                        {
                            //excuting
                            WarehouseLine warehouseLine = await context.warehouseLines.FirstOrDefaultAsync(x => x.WarehouseLineCode == taskOrder.WarehouseCode);
                            Box box = await context.boxs.FirstOrDefaultAsync(x => x.Id_Box == taskOrder.Id_Box);
                            //备用
                            Conveyorline conveyorline = await context.conveyorlines.FirstOrDefaultAsync(x => x.BoxCode == box.BoxCode);
                            if (conveyorline != null)
                            {
                                context.conveyorlines.Remove(conveyorline);
                                await context.SaveChangesAsync();
                            }
                        }
                    }
                }
                return new ApiResponseEss(0, "success", "Unable");
            }
            catch (SqlException ex)
            {
    
                loginHelper.LoginAsync(InPut, $"Sq+TaskStatusChange" + ex.Message);
                return new ApiResponseEss(0, "success", "Error");
            }
            catch (Exception ex)
            {
                InPut_BaseService15 inPut = new InPut_BaseService15();
                inPut.User = "ESS";
                inPut.Note = "任务编号：" + InPut.taskCode + "msg：" + InPut.message + "事件类型：" + InPut.eventType + "容器:" + InPut.containerCode +
                    "站点:" + InPut.stationCode + "状态：" + InPut.status + "异常:" + ex.ToString();
                inPut.Type = "异常";
                loginHelper.LoginAsync(InPut, $"TaskStatusChange任务回调-异常-{inPut.Note}");

                lognote lognote = new lognote()
                {
                    DateTime = DateTime.Now,
                    User = "ESS",
                    Type = "异常",
                    Note = "任务编号：" + InPut.taskCode + "msg：" + InPut.message + "事件类型：" + InPut.eventType + "容器:" + InPut.containerCode +
                    "站点:" + InPut.stationCode + "状态：" + InPut.status + "异常:" + ex.ToString()
                };
                return new ApiResponseEss(0, "success", "Error");
            }

        }//任务状态
        public async Task<ApiResponse> ReturnTag(InPut_EssService3 InPut)//灭灯
        {
            loginHelper.LoginInfoAsync("sss", $"ReturnTage-灭灯+{InPut.tagCode + InPut.display + InPut.eventCode}");
            lognote lognotetasknull = new lognote()
            {
                DateTime = DateTime.Now,
                User = "ESS",
                Type = "灭灯",
                Note = ($"灭灯-{InPut.tagCode + InPut.display + InPut.eventCode}")
            };
            await context.AddAsync(lognotetasknull);
            SowingWallLine sowingWallLine = await context.SowingWallLines.FirstOrDefaultAsync(x => x.SowingWallLine_Name== InPut.tagCode);
            if (sowingWallLine == null|| InPut.eventCode != "LIGHT_OFF")
            {
                loginHelper.LoginInfoAsync("sss",$"ReturnTage-未查询到灭灯任务+{InPut.tagCode + InPut.display + InPut.eventCode}");
                await context.SaveChangesAsync();
                return new ApiResponse("未查询到灭灯任务", false, null);
            }
            else
            {
                sowingWallLine.IsLight = false;
                await context.SaveChangesAsync();
                //signalr
                Tuple<string, HubConnection> tuple = await SingalrMethod.GetConnectionAsync("灭灯", null, null);
                loginHelper.LoginInfoAsync("sss", $"ReturnTag+success+灭灯成功+signalr{InPut.tagCode}");
                await tuple.Item2.StopAsync();
           
                return new ApiResponse("状态修改成功", true, null);

            }

        }
        public async Task<ApiResponseEss> Tote_finish(InPut_EssService4 InPut)//放箱完成上报
        {
            loginHelper.LoginInfoAsync(InPut, $"Tote_finish放箱+slotcode:{InPut.slotCode}" +
                $"containercode:{InPut.containerCode}");
            lognote lognote = new lognote()
            {
                DateTime = DateTime.Now,
                BoxCode = InPut.containerCode,
                Type = "Tote_finish放箱",
                User =" Tote_finish",
                Note = $"Tote_finish放箱-containerCode{InPut.containerCode}-slot{InPut.slotCode}"
            };
            await LogNote_res.InsertAsync(lognote);
            if (!string.IsNullOrEmpty(InPut.containerCode))
            {
                Box box=await box_res.FirstOrDefaultAsync(x=>x.BoxCode == InPut.containerCode);
                if (box != null)
                {
                    if (string.IsNullOrEmpty(box.Machine))
                    {
                        lognote lognote3 = new lognote()
                        {
                            DateTime = DateTime.Now,
                            BoxCode = InPut.containerCode,
                            Type = "Tote_finish机台号错误",
                            User = " Tote_finish",
                            Note = $"输送线上架-1-containerCode{InPut.containerCode}-slot{InPut.slotCode}"
                        };
                        await LogNote_res.InsertAsync(lognote3);
                        box.Machine = 1.ToString();
                    }
                    InPut_EssService5 essInPut5=new InPut_EssService5();
                    essInPut5.BoxCode = InPut.containerCode;
                    essInPut5.TaskType = $"下架-{box.Machine}";
                    essInPut5.Direction = box.Machine;
                    essInPut5.SlotCode=InPut.slotCode;
                    essInPut5.IsEss = true;
                    ApiResponse res = await baseService.moveContainer_wms(essInPut5);
                    if (res.State)
                    {
                        box.Machine = null;
                        await box_res.UpdateAsync(box);
     
                        return new ApiResponseEss(0, "success", "ok");
                    }
                    else
                    {
                        loginHelper.LoginInfoAsync( "null", $"Tote_finish放箱失败+slotcode:{InPut.slotCode}" +
                            $"containercode:{InPut.containerCode}+box.machine{box.Machine}");
                        lognote lognote2 = new lognote()
                        {
                            DateTime = DateTime.Now,
                            BoxCode = InPut.containerCode,
                            Type = "Tote_finish放箱失败",
                            User = " Tote_finish",
                            Note = $"输送线上架-1-containerCode{InPut.containerCode}-slot{InPut.slotCode}+box.machine{box.Machine}"
                        };
                        await LogNote_res.InsertAsync(lognote2);
                        return new ApiResponseEss(0, "success", "fail");
                    }


                }  
            }
            return new ApiResponseEss(0, "success", "unable");

        }

    }
}
